package com.example.pungolo.journal;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.example.pungolo.journal.model.DiaryIO;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.graphics.BitmapFactory.Options;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;

public class CameraActivity extends Activity {

  private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1;
  private static final int CROP_IMAGE_ACTIVITY_REQUEST_CODE = 6;
  private Uri newImageUri = null;
  private Uri currentImageUri = null;
  private Uri imageUri = null;

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    final Button saveButton = (Button) findViewById(R.id.cameraUI_save);
    final Button cancelButton = (Button) findViewById(R.id.cameraUI_cancel);
    final Button cropButton = (Button) findViewById(R.id.cameraUI_crop);
    final Button takePhotoButton = (Button) findViewById(R.id.cameraUI_takePhoto);

    cancelButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onCancelButtonClicked();
      }
    });

    cropButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onCropButtonClicked();
      }
    });

    saveButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onSaveButtonClicked();
      }
    });

    takePhotoButton.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        onTakePhotoButtonClicked();
      }
    });

    // set image
    ImageView picture = (ImageView) findViewById(R.id.cameraUI_pictureView);
    Intent caller = getIntent();
    String path = null;
    if (caller.hasExtra("imagePath"))
      path = caller.getStringExtra("imagePath");
    if (savedInstanceState != null && savedInstanceState.containsKey("imagePath"))
      path = savedInstanceState.getString("imagePath");
    
    if (path != null && new File(path).exists()) {

      imageUri = Uri.parse(path);
      picture.setImageURI(imageUri);
    }

    else
      start_camera();
  }

  protected void onSaveInstanceState(Bundle icicle) {
    super.onSaveInstanceState(icicle);
    if (imageUri != null)
      icicle.putString("imagePath", imageUri.getPath());

  }

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
        if (currentImageUri != null)
          deleteOldPicture(currentImageUri.getPath());

        currentImageUri = newImageUri;
        
        int inSample = 8;

        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inSampleSize = inSample;

        Bitmap b = BitmapFactory.decodeFile(newImageUri.getPath(), opts);
        File compressPhoto = new File(DiaryIO.getDiaryDirectory(), new Date().getTime() + "65" + ".jpg");

        boolean done = false;
        try {
          done = b.compress(CompressFormat.JPEG, 100, new FileOutputStream(compressPhoto));
        } catch (FileNotFoundException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
        if (done) {
          deleteOldPicture(currentImageUri.getPath());
          currentImageUri = Uri.parse(compressPhoto.getPath());
          imageUri = currentImageUri;
          Log.w("hdhdhd", "fatto");
        }
        imageUri = currentImageUri;
        ImageView picture = (ImageView) findViewById(R.id.cameraUI_pictureView);
        picture.setImageURI(imageUri);
      }

    } else if (resultCode == RESULT_CANCELED) {

    }

    else if (requestCode == CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
      if (resultCode == RESULT_OK) {
        Uri path = Uri.parse(data.getStringExtra("cropPath"));
        ImageView picture = (ImageView) findViewById(R.id.cameraUI_pictureView);
        picture.setImageURI(path);
      }

    } else if (resultCode == RESULT_CANCELED) {

    } else {
      // Image capture failed, advise user
    }
  }

  protected void onSaveButtonClicked() {
    if (imageUri != null) {

      Intent back = new Intent();
      back.putExtra(android.content.Intent.EXTRA_TEXT, imageUri.getPath());
      Log.w("picturePath", imageUri.getPath());
      this.setResult(RESULT_OK, back);
    }
    finish();
  }

  protected void onCropButtonClicked() {
    Intent cropIntent = new Intent(getApplicationContext(), CropActivity.class);
    cropIntent.putExtra("picturePath", imageUri.getPath());
    startActivityForResult(cropIntent, CROP_IMAGE_ACTIVITY_REQUEST_CODE);
  }

  protected void onTakePhotoButtonClicked() {

    start_camera();
  }

  protected void onCancelButtonClicked() {
    if (currentImageUri != null)
      deleteOldPicture(currentImageUri.getPath());
    finish();
  }

  private void start_camera() {
    Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File dir = DiaryIO.getDiaryDirectory();
    File photo = new File(dir, new Date().getTime() + ".jpg");
    newImageUri = Uri.fromFile(photo); // create a file to
    Log.w("newImageUri", newImageUri.getPath());
    camera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo)); // set the
                                                                   // image file
    // name

    // start the image capture Intent
    startActivityForResult(camera, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

  }

  private void deleteOldPicture(String picturePath) {
    if (picturePath == null)
      return;
    File f = new File(picturePath);

    // Make sure the file or directory exists and isn't write protected
    if (!f.exists())
      return;

    // Attempt to delete it
    f.delete();

  }

}